from flask import render_template, request, redirect, url_for
from app import app
from .config import ver
from .database import Message
from .database import db
from .forms import MessageForm, message_add_id


@app.route("/cke")
def cke():
    return render_template("static/ckeditor/samples/index.html")


@app.route('/', methods=('GET', 'POST'))
@app.route('/index/<page_show>', methods=('GET', 'POST'))
def index(page_show=None):
    message_show_each_page = 5

    form = MessageForm()
    if form.validate_on_submit():
        if form.uuid.data == message_add_id:
            message = Message(form.nickname.data, form.message_submitted.data)
            db.session.add(message)
            db.session.commit()
        else:
            message = Message.query.filter_by(uuid=form.uuid.data).first()
            if message is not None:
                message.message = form.message_submitted.data
                message.nickname = form.nickname.data
                db.session.commit()

    message_sum = Message.query.count()
    page_sum = (message_sum + message_show_each_page - 1) / message_show_each_page
    page_sum = int(page_sum)

    if page_show is None:
        page = request.args.get('page')
        try:
            page = int(page)
        except (TypeError, ValueError):
            page = 1
    else:
        page = int(page_show)
    if page < 1 or page > page_sum:
        page = 1

    this_page_start_message = (page - 1) * message_show_each_page
    messages = Message.query.order_by(Message.id.desc()).slice(
        this_page_start_message,
        this_page_start_message + message_show_each_page)

    return render_template(
        "index.html",
        title="123qer",
        ver=ver,
        messages=messages,
        form=MessageForm(),
        page=page,
        page_sum=page_sum)


@app.route("/delete_message")
def delete_message():
    message_id = request.args.get("message_id")
    if message_id is not None:
        message = Message.query.filter_by(uuid=message_id).first()
        if message:
            db.session.delete(message)
            db.session.commit()

    page = request.args.get("page")
    if page is None:
        page = 1
    return redirect(url_for("index", page_show=page))